package logic

import (
	"context"
	"errors"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"github.com/eeppee_admin/clouddisk/service/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFileNameUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFileNameUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFileNameUpdateLogic {
	return &UserFileNameUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFileNameUpdateLogic) UserFileNameUpdate(req *types.UserFileNameUpdateRequest) (resp *types.UserFileNameUpdateResponse, err error) {
    // 判断当前文件名称在该层级下是否存在
    cnt, err := l.svcCtx.Engine.
        Where("name = ? AND parent_id = (select parent_id from userstore where userstore.identity = ?)", req.Name, req.Identity).
        Count(new(model.UserStore))

    if err != nil {
        return nil, err
    }
    if cnt > 0 {
        return nil, errors.New("文件名已经存在")
    }

    // 文件名称修改
    userStore := &model.UserStore{Name: req.Name}
    _, err = l.svcCtx.Engine.
        Where("identity = ? AND user_identity = ?", req.Identity, userStore.UserIdentity).
        Update(userStore)
    if err != nil {
        return nil, err
    }


    return
}